package org.dcma.server;

import java.util.List;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;

import org.dcma.client.Departamento;

public class DepartamentoJdoDAO implements DepartamentoDAO {

	private static final PersistenceManagerFactory pmfInstance = JDOHelper
	.getPersistenceManagerFactory("transactions-optional");

	public static PersistenceManagerFactory getPersistenceManagerFactory() {
		return pmfInstance;
	}
	
	@Override
	public void addDepartamento(Departamento departamento) {
		PersistenceManager pm = getPersistenceManagerFactory()
		.getPersistenceManager();
		try {
			pm.makePersistent(departamento);
		} finally {
			pm.close();
		}

	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Departamento> listDepartamentos() {
		PersistenceManager pm = getPersistenceManagerFactory()
		.getPersistenceManager();
		String query = "select from " + Departamento.class.getName();
		return (List<Departamento>) pm.newQuery(query).execute();
	}

	@Override
	public void removeDepartamento(Departamento departamento) {
		PersistenceManager pm = getPersistenceManagerFactory()
		.getPersistenceManager();
		try {
			pm.currentTransaction().begin();
		
			// We don't have a reference to the selected Departamento.
			// So we have to look it up first,
			departamento = pm.getObjectById(Departamento.class, departamento.getId());
			pm.deletePersistent(departamento);
		
			pm.currentTransaction().commit();
		} catch (Exception ex) {
			pm.currentTransaction().rollback();
			throw new RuntimeException(ex);
		} finally {
			pm.close();
		}
	}

	@Override
	public void updateDepartamento(Departamento departamento) {
		PersistenceManager pm = getPersistenceManagerFactory()
		.getPersistenceManager();
		String name = departamento.getNombre();
		
		try {
			pm.currentTransaction().begin();
			// We don't have a reference to the selected Product.
			// So we have to look it up first,
			departamento = pm.getObjectById(Departamento.class, departamento.getId());
			departamento.setNombre(name);
			pm.makePersistent(departamento);
			pm.currentTransaction().commit();
		} catch (Exception ex) {
			pm.currentTransaction().rollback();
			throw new RuntimeException(ex);
		} finally {
			pm.close();
		}

	}

}
